<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form
        :model="query"
        inline size="mini"
        class="ele-form-search"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <el-form-item label="省市区:">
          <el-cascader
              clearable
              v-model="city"
              class="ele-fluid"
              placeholder="请选择省市区"
              :options="regions.cityData"
              popper-class="ele-pop-wrap-higher"/>
        </el-form-item>
        <el-form-item label="街道:">
          <el-select style="width:100%" clearable
                     :disabled="!query.district_code"
                     v-model="query.streets_code"
                     placeholder="请输入街道">
            <el-option :value="item.streets_code" :label="item.ext_name" v-for="(item,index) in streetsList" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属学校:">

          <el-select style="width:100%" clearable
                     :disabled="!query.streets_code"
                     v-model="query.schoole_id"
                     placeholder="请输入所属学校">
            <el-option :value="item.id" :label="item.title" v-for="(item,index) in schoolList" :key="index"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色:">
          <el-select
              multiple
              clearable
              class="ele-block"
              v-model="query.role_id"
              placeholder="请选择角色">
            <el-option
                v-for="item in roleList"
                :key="item.id"
                :value="item.id"
                :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="性别:">
          <el-select
              clearable
              v-model="query.gender"
              placeholder="请选择性别"
              class="ele-fluid">
            <el-option label="男" value="1"/>
            <el-option label="女" value="2"/>
            <el-option label="保密" value="3"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              icon="el-icon-search"
              class="ele-btn-icon"
              @click="reload">查询
          </el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="toolbar-box" style="margin-bottom:4px;">
        <div class="tool-btn">
          <!-- <el-button
            @click="showImport=true"
            icon="el-icon-upload2"
            class="ele-btn-icon"
            size="small">导入
          </el-button> -->
          <el-button
            size="mini"
            type="default"
            icon="el-icon-download"
            class="ele-btn-icon"
            @click="exportExcel">导出
          </el-button>
        </div>
        <div class="tool-tab">
          <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              class="ele-btn-icon"
              :disabled="!selection.length"
              @click="removeBatch">删除
          </el-button>
          <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="openEdit(null)">添加
          </el-button>
        </div>
      </div>
        <!-- 数据表格 -->
        <el-table
        border
        lazy
        ref="table"
        :data="data"
        v-loading="loading"
        height="calc(100vh - 315px)"
         @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
        <el-table-column label="序号" width="55" align="center" type="index">
          <template slot-scope="scope">
            <span
              v-text="$setTableIndex(query.page, query.limit, scope.$index)"
            >
            </span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center" prop="realname" />
        <el-table-column label="账户名称" align="center" prop="username" />
        <el-table-column label="角色" align="center" prop="roles">
           <template slot-scope="scope">{{getRoles(scope.row.roles)}}</template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" prop="mobile" />
        <el-table-column label="所在省" align="center" prop="province_name" />
        <el-table-column label="所在市" align="center" prop="city_name" />
        <el-table-column label="所在县区" align="center" prop="district_name" />
        <el-table-column label="所在街道" align="center" prop="streets_name" />
        <el-table-column label="所在学校" align="center" prop="schoole_name" />
        <el-table-column label="性别" align="center" prop="gender_name" />
        <el-table-column label="创建时间" align="center" prop="create_time">
           <template slot-scope="scope">{{$util.toDateString(scope.row.create_time)}}</template>
        </el-table-column>
        <el-table-column
        label="操作"
        align="center"
        fixed="right"
         width="150"
        :resizable="true"
      >
      <template slot-scope="{row}">
        <el-link
            type="text"
            :underline="false"
            icon="el-icon-edit"
            @click="openEdit(row)">修改
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此用户吗？"
            @confirm="remove(row)">
            <el-link
              type="text"
              slot="reference"
              :underline="false"
              icon="el-icon-delete">删除
            </el-link>
          </el-popconfirm>
          <!-- <el-popconfirm
            class="ele-action"
            title="确定要重置密码吗？"
            @confirm="resetPwd(row)">
            <el-link
              type="text"
              slot="reference"
              :underline="false"
              icon="el-icon-copy-document">重置密码
            </el-link>
          </el-popconfirm> -->
        </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="total"
        :page.sync="query.page"
        :limit.sync="query.limit"
        @pagination="getData"
      />
   </el-card>
    <!-- 编辑弹窗 -->
    <user-edit
      :data="current"
      :visible.sync="showEdit"
      @done="reload"/>
      <!-- 导入弹窗 -->
    <user-import
      :visible.sync="showImport"
      @done="reload"/>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import UserEdit from './user-edit';
import regions from 'ele-admin/packages/regions';
import UserImport from './user-import'

export default {
  name: 'SystemUser',
  components: {UserEdit,UserImport},
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      // 省市区数据
      regions: regions,
      // 选中的省市区
      city: [],
      loading: false, // 表格加载状态
      selection: [], // 表格选中数据
      total: 0, // 数据总数
      data: [], // 表格数据接口
      // 表格搜索条件
      query: {
        page: 1,
        limit: 10,
        province_code:'',
        city_code:'',
        district_code:'',
        streets_code:'',
        schoole_id:'',
        role_id:'',
        gender:''
      },
      roleList: [],
      streetsList: [],
      schoolList: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 是否显示导入弹窗
      showImport: false
    };
  },
  mounted() {
    this.getData();
    this.queryRoles();
  },
  watch: {
    city(val) {
      if (val && val.length > 0) { 
        this.query.province_code=val[0]
        this.query.city_code=val[1]
        this.query.district_code = val[2]
        if (this.query.district_code) {
          this.getStreetsList()
        }
      }
    },
    'query.streets_code': {
      handler: function (newVal,oldVal) { 
        console.log("111--newVal", newVal,oldVal)
            this.getSchoolList()
      },
      deep:true
     }
  },
  methods: {
    getRoles(roles) { 
      if (roles && roles.length > 0) {
        return roles.map(d => d.name).join(',')
      } else { 
        return []
      }
    },
    /* 查询角色列表 */
   queryRoles() {
      this.$http.get('/role/getRoleList').then(res => {
        if (res.data.code === 0) {
          this.roleList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    getStreetsList() {
      this.$http
        .get("/user/getStreetsList", { params: { district_code: this.query.district_code } })
        .then(res => {
          this.streetsList = res.data.data;
        })
        .catch(e => {
          this.$message.error(e.message);
        });
    },
    getSchoolList() {
      this.$http
        .get("/user/getSchoolList", { params: { streets_code: this.query.streets_code } })
        .then(res => {
          this.schoolList = res.data.data;
        })
        .catch(e => {
          this.$message.error(e.message);
        });
    },
   
     /* 获取表格数据 */
     getData() {
      this.loading = true;
      this.$http
        .get("/user/index", { params: this.query })
        .then(res => {
          this.loading = false;
          this.total = res.data.count;
          this.data = res.data.data;
        })
        .catch(e => {
          this.loading = false;
          this.$message.error(e.message);
        });
    },
     /* 查询数据 */
     reload() {
      this.getData();
    },
    /* 重置搜索 */
    reset() {
      this.query = {
        page: 1,
        limit: 10
      };
      this.reload();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    /* 显示编辑 */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    /* 删除 */
    remove(row) {
      const loading = this.$loading({lock: true});
      this.$http.post('/user/delete', {id: row.id}).then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 批量删除 */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据')
        return;
      }
      this.$confirm('确定要删除选中的用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({lock: true});
        this.$http.post('/user/delete', {id: this.selection.map(d => d.id)}).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg});
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      }).catch(() => {
      });
    },
    /* 导出数据Excel */
    exportExcel() {
      let info = JSON.parse(JSON.stringify(this.query));
      this.$http
        .get("/user/exportExcel", info)
        .then((res) => {
          let data = res.data;
          if (data.code == 0) {
            // 下载文件
            window.location.href = data.data;
            this.$message({
              type: "success",
              message: "导出成功",
            });
          } else {
            this.$message.error("导出失败");
          }
        })
    },
    /**
     * 重置密码
     */
    resetPwd(row){
      const loading = this.$loading({lock: true});
        this.$http.post('/user/resetPwd', {id: row.id}).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg});
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
    },
  }
}
</script>

<style scoped>
.toolbar-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
